package com.atwisdom.star.core.dsl.modelClass.routing.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.enums.RoutingStatusEnum;
import com.atwisdom.star.common.vo.ModelType;
import com.atwisdom.star.common.vo.PageInfo;
import com.atwisdom.star.core.dao.pojo.modelClass.hier.HierInstance;
import com.atwisdom.star.core.dao.pojo.modelClass.hier.HierInstanceUtils;
import com.atwisdom.star.core.dao.pojo.modelClass.hier.HierModel;
import com.atwisdom.star.core.dao.pojo.modelClass.logic.LogicModel;
import com.atwisdom.star.core.dao.pojo.modelClass.routing.RoutingInstance;
import com.atwisdom.star.core.dao.pojo.modelClass.routing.RoutingInstanceHistory;
import com.atwisdom.star.core.dao.pojo.modelClass.routing.RoutingModel;
import com.atwisdom.star.core.dao.pojo.modelClass.workCenter.WorkCenterInstance;
import com.atwisdom.star.core.dao.service.modelClass.routing.RoutingInstanceHistoryService;
import com.atwisdom.star.core.dao.service.modelClass.routing.RoutingInstanceService;
import com.atwisdom.star.core.dao.service.modelClass.routing.RoutingModelService;
import com.atwisdom.star.core.dsl.cache.ModelCacheDslService;
import com.atwisdom.star.core.dsl.modelClass.hier.Impl.HierInstanceDslServiceImpl;
import com.atwisdom.star.core.dsl.modelClass.hier.Impl.HierModelDslServiceImpl;
import com.atwisdom.star.core.dsl.modelClass.routing.RoutingInstanceDslService;
import com.atwisdom.star.core.dsl.modelClass.utils.QueryBuilder;
import com.atwisdom.star.core.dsl.modelClass.workCenter.Impl.WorkCenterInstanceDslServiceImpl;
import com.atwisdom.star.exception.pojo.BusinessException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Service
public class RoutingInstanceDslServiceImpl implements RoutingInstanceDslService {
    private RoutingModelService routingModelService;
    private RoutingInstanceService routingInstanceService;
    private RoutingInstanceHistoryService routingInstanceHistoryService;

    private WorkCenterInstanceDslServiceImpl workCenterInstanceDslService;

    private HierInstanceDslServiceImpl hierInstanceDslService;

    private HierModelDslServiceImpl hierModelDslService;

    private QueryBuilder queryBuilder;

    private ModelCacheDslService modelCacheDslService;

    @Autowired
    public void setModelCacheDslService(ModelCacheDslService modelCacheDslService) {
        this.modelCacheDslService = modelCacheDslService;
    }

    @Autowired
    public void setRoutingModelService(RoutingModelService routingModelService) {
        this.routingModelService = routingModelService;
    }

    @Autowired
    public void setRoutingInstanceService(RoutingInstanceService routingInstanceService) {
        this.routingInstanceService = routingInstanceService;
    }
    @Autowired
    public void setWorkCenterInstanceDslService(WorkCenterInstanceDslServiceImpl workCenterInstanceDslService) {
        this.workCenterInstanceDslService = workCenterInstanceDslService;
    }

    @Autowired
    public void setRoutingInstanceHistoryService(RoutingInstanceHistoryService routingInstanceHistoryService) {
        this.routingInstanceHistoryService = routingInstanceHistoryService;
    }
    @Autowired
    public void setHierInstanceDslService(HierInstanceDslServiceImpl hierInstanceDslService) {
        this.hierInstanceDslService = hierInstanceDslService;
    }

    @Autowired
    public void setHierModelDslService(HierModelDslServiceImpl hierModelDslService) {
        this.hierModelDslService = hierModelDslService;
    }

    @Autowired
    public void setQueryBuilder(QueryBuilder queryBuilder) {
        this.queryBuilder = queryBuilder;
    }


    /**
     * 查询全部摘要（通用）
     * @return 返回搞要列表
     */
    @Override
    public List<JSONObject> queryAllInfo() {
        try {
            QueryWrapper<RoutingInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published",true);
            queryBuilder.buildInfoSelection(queryWrapper);
            queryBuilder.buildOrderBy(queryWrapper, null, "className,updateTime");
            List<RoutingInstance> list = routingInstanceService.list();
            List<JSONObject> jsonObjectList = new ArrayList<>();
            list.forEach(ins-> jsonObjectList.add(ins.getInfoJsonObject()));
            return jsonObjectList;
        }catch (Exception ex){
            throw new BusinessException("999999", "无条件查询所有模型信息！");
        }
    }

    /**
     * 分页查询全部摘要（通用）
     * @param pageNumber 参数
     * @param pageSize 参数
     * @param orderBy 参数
     * @return 返回全部搞要列表
     */
    @Override
    public PageInfo queryAllInfoByPage(int pageNumber, int pageSize, String orderBy) {
        try {
            Page<RoutingInstance> pageInfo = new Page<>(pageNumber, pageSize);
            QueryWrapper<RoutingInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published",true);
            queryBuilder.buildInfoSelection(queryWrapper);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            return getPageInfoResult(pageInfo, queryWrapper,true);
        }catch (Exception ex){
            throw new BusinessException("999999", "分页无条件查询摘要模型信息！",ex);
        }
    }

    /**
     * 查询全部数据（通用）
     *
     * @return 返回结果
     */
    @Override
    public List<JSONObject> queryAll() {
        try {
            QueryWrapper<RoutingInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published",true);
            queryBuilder.buildOrderBy(queryWrapper,null,"className,updateTime");
            List<RoutingInstance> list = routingInstanceService.list();
            list.forEach(l->{
                List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Routing.getCode(), l.getClassName(), l.getId());
                List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Routing.getCode(), l.getClassName());
                l.setHierModels(hierModels);
                l.setHierInstances(hierInstances);
            });

            return this.getRoutingInsJsonObjectList(list);
        }catch (Exception ex){
            throw new BusinessException("999999", "无条件查询所有模型信息！");
        }
    }

    /**
     * 分页无条件查询模型信息
     *
     * @param pageNumber 参数
     * @param pageSize 参数
     * @param orderBy 参数
     * @return 返回值
     */
    @Override
    public PageInfo listAllByPage(int pageNumber,int pageSize,String orderBy) {
        try {
            Page<RoutingInstance> pageInfo = new Page<>(pageNumber, pageSize);
            QueryWrapper<RoutingInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published",true);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            return getPageInfoResult(pageInfo, queryWrapper,false);
        }catch (Exception ex){
            throw new BusinessException("999999", "分页无条件查询模型信息！");
        }
    }

    /**
     * 查询模型
     *
     * @param condition 查询参数
     * @param className 查询参数
     * @param orderBy 排序参数
     * @return 返回值
     */
    @Override
    public List<JSONObject> query(String condition,String className,String orderBy) {
        try{
            if (StringUtils.isBlank(className)) {
                className = queryBuilder.getClassNameBy(condition);
            }
            condition = queryBuilder.transformOperator(condition);
            condition = this.transformConditionForRouting(condition,className);
            orderBy =   this.transformOrderByForRouting(condition,className,orderBy);
            QueryWrapper<RoutingInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotBlank(className),"className", className);
            queryWrapper.eq("published", true);
            queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            List<RoutingInstance> list = routingInstanceService.list(queryWrapper);
            list.forEach(l->{
                List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Routing.getCode(), l.getClassName(), l.getId());
                List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Routing.getCode(), l.getClassName());
                l.setHierInstances(hierInstances);
                l.setHierModels(hierModels);
            });
            return this.getRoutingInsJsonObjectList(list);
        }catch (Exception ex){
            throw new BusinessException("999999", "查询模型失败！",ex);
        }
    }

    /**
     * 根据className获取实例数据
     *
     * @param className 参数
     * @return 返回实例
     */
    public List<RoutingInstance> queryByClassName(String className) {
        LambdaQueryWrapper<RoutingInstance> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoutingInstance::getClassName,className);
        wrapper.eq(RoutingInstance::getPublished,true);
        List<RoutingInstance> list = this.routingInstanceService.list(wrapper);
        List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Routing.getCode(), className);
        list.forEach(l->{
            List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Routing.getCode(), className, l.getId());
            l.setHierModels(hierModels);
            l.setHierInstances(hierInstances);
        });
        return list;
    }

    /**
     * 根据id获取实例数据
     *
     * @param id 主键id
     * @return 返回实例
     */
    public RoutingInstance queryById(Long id) {
        return this.routingInstanceService.getById(id);
    }

    /**
     * 根据id获取实例数据
     *
     * @param id 主键id
     * @return 返回实例
     */
    public JSONObject queryJsonById(Long id) {
        RoutingInstance instance = this.routingInstanceService.getById(id);
        List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Routing.getCode(), instance.getClassName());
        List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Routing.getCode(), instance.getClassName(), instance.getId());
        instance.setHierModels(hierModels);
        instance.setHierInstances(hierInstances);
        return getRoutingInsJsonObjectList(Arrays.asList(instance)).get(0);
    }
    /**
     * 根据id获取实例数据
     *
     * @param ids 主键ids
     * @return 返回实例json
     */
    public List<JSONObject> queryByIds(List<Long> ids) {
        LambdaQueryWrapper<RoutingInstance> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(RoutingInstance::getId,ids);
        List<RoutingInstance> routingInstanceList = routingInstanceService.list(wrapper);
        routingInstanceList.forEach(l->{
            List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Routing.getCode(), l.getId(),  l.getClassName(), null);
            List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Routing.getCode(), l.getClassName());
            l.setHierInstances(hierInstances);
            l.setHierModels(hierModels);
        });
        return getRoutingInsJsonObjectList(routingInstanceList);
    }
    /**
     * 根据id获取实例数据及关联的hier数据
     *
     * @param id 主键id
     * @return 返回实例
     */
    public RoutingInstance queryInsWithHierById(Long id) {
        if (id!=null) {
            RoutingInstance routingInstance = this.routingInstanceService.getById(id);
            if (routingInstance!=null) {
                List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Routing.getCode(), routingInstance.getId(),  routingInstance.getClassName(), null);
                List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Routing.getCode(), routingInstance.getClassName());
                routingInstance.setHierInstances(hierInstances);
                routingInstance.setHierModels(hierModels);
            }
            return routingInstance;
        } else {
            return null;
        }
    }

    /**
     * 更新状态
     * @param id 实例id
     * @param statusCode 状态
     */
    @Override
    public void updateStatus(Long id, String statusCode) {
        RoutingInstance routingInstance = getById(id);
        routingInstance.setSt0(statusCode);
        updateById(routingInstance);
    }

    /**
     * 查询实例容器hier
     * @param id 参数
     * @return 返回hier
     */
    public JSONObject queryHierById(long id) {
        try {
            RoutingInstance routingInstance = this.routingInstanceService.getById(id);
            List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Routing.getCode(), routingInstance.getClassName(), id);
            List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Routing.getCode(), routingInstance.getClassName());
            HierInstanceUtils hierInstanceUtils = new HierInstanceUtils(hierInstances, hierModels);
            return hierInstanceUtils.fetchHier();
        } catch (Exception ex) {
            throw new BusinessException("999999", "查询容器信息失败！");
        }
    }

    /**
     * 按条件分页查询实例摘要
     *
     * @param pageNumber 查询参数
     * @param pageSize 查询参数
     * @param condition 查询参数
     * @param className 查询参数
     * @param orderBy 排序参数
     * @return 返回值
     */
   public PageInfo queryInfoByPage(int pageNumber,int pageSize, String condition,String className,String orderBy){
       try {
           if (StringUtils.isBlank(className)) {
               className = queryBuilder.getClassNameBy(condition);
           }
           Page<RoutingInstance> pageInfo = new Page<>(pageNumber, pageSize);
           condition = queryBuilder.transformOperator(condition);
           condition = this.transformConditionForRouting(condition,className);
           orderBy =   this.transformOrderByForRouting(condition,className,orderBy);
           QueryWrapper<RoutingInstance> queryWrapper = new QueryWrapper<>();
           queryWrapper.eq(StringUtils.isNotBlank(className),"className", className);
           queryWrapper.eq("published", true);
           queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
           queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
           return getPageInfoResult(pageInfo, queryWrapper,true);
       }catch (Exception ex){
           throw new BusinessException("999999", "分页无条件查询模型信息！");
       }
    }

    /**
     * 按条件分页查询实例
     *
     * @param pageNumber 查询参数
     * @param pageSize 查询参数
     * @param condition 查询参数
     * @param className 查询参数
     * @param orderBy 排序参数
     * @return 返回值
     */
    public PageInfo queryByPage(int pageNumber,int pageSize, String condition,String className,String orderBy){
        try {
            if (StringUtils.isBlank(className)) {
                className = queryBuilder.getClassNameBy(condition);
            }
            Page<RoutingInstance> pageInfo = new Page<>(pageNumber, pageSize);
            condition = queryBuilder.transformOperator(condition);
            condition = this.transformConditionForRouting(condition,className);
            orderBy =   this.transformOrderByForRouting(condition,className,orderBy);
            QueryWrapper<RoutingInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotBlank(className),"className", className);
            queryWrapper.eq("published", true);
            queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            return getPageInfoResult(pageInfo, queryWrapper,false);
        }catch (Exception ex){
            throw new BusinessException("999999", "分页无条件查询模型信息！");
        }
    }
    /**
     * 按条件分页查询实例
     *
     * @param pageNumber 查询参数
     * @param pageSize 查询参数
     * @param condition 查询参数
     * @param className 查询参数
     * @param orderBy 排序参数
     * @return 返回值
     */
    public PageInfo queryByPage(int pageNumber,int pageSize, String condition,String className,String orderBy, String hierValueCondition){
        try {
            if (StringUtils.isBlank(className)) {
                className = queryBuilder.getClassNameBy(condition);
            }
            Page<RoutingInstance> pageInfo = new Page<>(pageNumber, pageSize);
            condition = queryBuilder.transformOperator(condition);
            condition = this.transformConditionForRouting(condition,className);
            orderBy =   this.transformOrderByForRouting(condition,className,orderBy);
            QueryWrapper<RoutingInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotBlank(className),"className", className);
            queryWrapper.eq("published", true);
            queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            if (StrUtil.isNotBlank(hierValueCondition)) {
                hierValueCondition = hierValueCondition.replace("'$", "insValues->'$");
            }
            return getPageInfoResult(pageInfo, queryWrapper,false, hierValueCondition);
        }catch (Exception ex){
            throw new BusinessException("999999", "分页无条件查询模型信息！");
        }
    }

    /**
     * 添加模型
     *
     * @param type 参数
     * @param className 参数
     * @param name 参数
     * @return 返回值
     */
    @Override
    public JSONObject add(String type, String className,String name,JSONObject values) {
        RoutingInstance instance = buildNewRoutingInstance(type, className, name, values);
        RoutingModel routingModel = this.modelCacheDslService.queryModel(ModelType.Routing.getCode(), className);
        this.add(instance);
        return instance.getInsJsonObject(routingModel);
    }

    /**
     * 保存新实例
     * @param newInstance 新实例
     * @return 返回添加后的实例
     */
    public RoutingInstance add(RoutingInstance newInstance){
        this.routingInstanceService.save(newInstance);
        List<HierInstance> hierInstances = this.hierInstanceDslService.add(ModelType.Routing.getCode(), newInstance.getClassName(), newInstance.getId());
        List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Routing.getCode(), newInstance.getClassName());
        newInstance.setHierInstances(hierInstances);
        newInstance.setHierModels(hierModels);
        //添加历史
        RoutingInstanceHistory routingInstanceHistory = new RoutingInstanceHistory();
        BeanUtils.copyProperties(newInstance, routingInstanceHistory);
        routingInstanceHistory.setId(null);
        routingInstanceHistoryService.save(routingInstanceHistory);
        return newInstance;
    }

    /**
     * 保存新实例
     * @param insJson 新实例Json
     * @return 返回添加后的实例JSON
     */
    public JSONObject add(JSONObject insJson) {
        String className = insJson.getString("className");
        RoutingModel routingModel = this.modelCacheDslService.queryModel(ModelType.Routing.getCode(), className);

        RoutingInstance instance = new RoutingInstance(routingModel, insJson);
        this.add(instance);
        return instance.getInsJsonObject(routingModel);
    }


    /**
     * 构建新实例数据对象
     *
     * @param className 类名
     * @param name      名称
     * @return 返回构建的新实例
     */
    public RoutingInstance buildNewRoutingInstance(String className, String name) {
        return this.buildNewRoutingInstance("routing", className, name, null);
    }

    /**
     * 构建新实例数据对象
     * @param type 类型
     * @param className 类名
     * @param name 名称
     * @param values 实体值
     * @return 返回构建的新实例
     */
   public RoutingInstance  buildNewRoutingInstance(String type, String className,String name,JSONObject values){
       if (!existModel(type, className)) {
           throw new BusinessException("999999", "模型不存在,创建实例失败！");
       }
       if(values==null){
           values = new JSONObject();
       }
       RoutingModel routingModel = this.modelCacheDslService.queryModel(ModelType.Routing.getCode(), className);
       JSONObject insJsonObject = new JSONObject();
       insJsonObject.put("type", type);
       insJsonObject.put("name", name);
       insJsonObject.put("className", className);
       insJsonObject.put("published", true);
       insJsonObject.put("version", routingModel.getVersion());
       insJsonObject.put("values", values);
       insJsonObject.put("web", new JSONObject());
       insJsonObject.put("others", new JSONObject());
       insJsonObject.put("st0", RoutingStatusEnum.RUNNING.getCode());

       return new RoutingInstance(routingModel, insJsonObject);
   }

    public RoutingInstance  buildNewRoutingInstance(JSONObject jsonObject){
        String className = jsonObject.getString("className");
        String type = jsonObject.getString("type");
        if (!existModel(type, className)) {
            throw new BusinessException("999999", "模型不存在,创建实例失败！");
        }
        RoutingModel routingModel = this.modelCacheDslService.queryModel(ModelType.Routing.getCode(), className);
        return new RoutingInstance(routingModel, jsonObject);
    }

    public  List<HierModel> initRoutingWorkCenterInstances(RoutingInstance instance){
        List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Routing.getCode(), instance.getClassName());
        hierModels.forEach(hm->{
            if(hm.getLinkId()==null && StringUtils.isNotBlank(hm.getLinkType()) && StringUtils.isNotBlank(hm.getLinkClassName())){
                WorkCenterInstance workCenterInstance = this.workCenterInstanceDslService.buildNewWorkCenterInstance(hm.getLinkClassName(),hm.getName());
                this.workCenterInstanceDslService.add(workCenterInstance);
                // this.hierInstanceDslService.add(ModelType.WorkCenter.getCode(),workCenterInstance.getClassName(),workCenterInstance.getId());
                Long id = workCenterInstance.getId();
                hm.setLinkId(id);
            }
        });
        return hierModels;
    }


    /**
     * 更新模型属性字段
     * 更新，需要同步更新实例，同步更新历史数据
     * 1、className 和 自定字段
     *
     * @param jsonObject 参数
     * @return 返回值
     */
    @Override
    public JSONObject updateById(JSONObject jsonObject) {
        try {
            RoutingInstance instance = this.buildUpdateInstance(jsonObject);
            RoutingModel routingModel = this.modelCacheDslService.queryModel(ModelType.Routing.getCode(), instance.getClassName());
            this.updateById(instance);
            return instance.getInsJsonObject(routingModel);
        }catch (Exception ex){
            throw new BusinessException("999999", "更新模型实例失败！");
        }
    }

    public void updateFieldNullById(JSONObject jsonObject){
        String className = jsonObject.getString("className");
        Long id = jsonObject.getLong("id");
        LogicModel logicModel = this.modelCacheDslService.queryModel(ModelType.Logic.getCode(), className);
        JSONObject values = jsonObject.getJSONObject("values");
        JSONObject features = logicModel.fetchFeatures();
        UpdateWrapper<RoutingInstance> updateWrapper = new UpdateWrapper<>();
        // 遍历 JSONObject 对象
        for (String key : features.keySet()) {
            String v = values.getString(key);
            if(StringUtils.isBlank(v)){
                updateWrapper.set(key, null);
            }
        }
        updateWrapper.eq("id",id);
        routingInstanceService.update(updateWrapper);
    }

    public RoutingInstance  buildUpdateInstance(JSONObject jsonObject){
        String id = jsonObject.getString("id");
        if(StringUtils.isBlank(id)){
            throw new BusinessException("999999", "更新id为空操作失败！");
        }

        RoutingInstance sourceInstance = routingInstanceService.getById(id);
        if(sourceInstance==null){
            throw new BusinessException("999999", "要更新实例不存在，操作失败！");
        }
        JSONObject sourceInstanceJson = getRoutingInsJsonObjectList(Arrays.asList(sourceInstance)).get(0);
        String className = jsonObject.getString("className");
        String type = jsonObject.getString("type");
        if (!existModel(type, className)) {
            throw new BusinessException("999999", "模型不存在,创建实例失败！");
        }
        RoutingModel routingModel = this.modelCacheDslService.queryModel(ModelType.Routing.getCode(), sourceInstance.getClassName());
        return new RoutingInstance(routingModel,jsonObject,sourceInstanceJson.getJSONObject("values"));
    }

    /**
     * 更新模型属性字段
     * 更新，需要同步更新实例，同步更新历史数据
     * @param routingInstance 参数
     * @return 返回值
     */
    public RoutingInstance updateById(RoutingInstance routingInstance){
        try {
            routingInstanceService.getBaseMapper().updateById(routingInstance);
            List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Routing.getCode(), routingInstance.getClassName());
            List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Routing.getCode(), routingInstance.getClassName(), routingInstance.getId());
            routingInstance.setHierInstances(hierInstances);
            routingInstance.setHierModels(hierModels);
            //添加历史
            RoutingInstance newLogicInstance = this.routingInstanceService.getById(routingInstance.getId());
            RoutingInstanceHistory routingInstanceHistory = new RoutingInstanceHistory();
            BeanUtils.copyProperties(newLogicInstance,routingInstanceHistory);
            routingInstanceHistory.setId(null);
            this.routingInstanceHistoryService.save(routingInstanceHistory);
            return routingInstance;
        }catch (Exception ex){
            throw new BusinessException("999999", "更新模型实例失败！");
        }
    }

    /**
     * 更新模型属性字段
     * 更新，需要同步更新实例，同步更新历史数据
     * 1、className 和 自定字段
     *
     * @param jsonObjectList 参数
     * @return 返回值
     */
    @Override
    public List<JSONObject> updateByIds(List<JSONObject> jsonObjectList) {
        List<JSONObject> resultJsonList = new ArrayList<>();
        jsonObjectList.forEach(j->{
            JSONObject jsonObject = this.updateById(j);
            resultJsonList.add(jsonObject);

        });
        return resultJsonList;
    }

    /**
     * 按类型和类名更新模型实例（配置阶段）
     * @param jsonObject 类型
     * @return 返回模型记录
     */
    @Override
    public List<JSONObject> updateClassName(JSONObject jsonObject) {
        String type = jsonObject.getString("type");
        String className = jsonObject.getString("className");
        if (StringUtils.isBlank(type) || StringUtils.isBlank(className)) {
            throw new BusinessException("999999", "更新模型实例：type,className都不能为空！");
        }

        if (!this.existModel(type, className)) {
            throw new BusinessException("999999", "模型不存在，更新模型实例失败！");
        }

        try {
            QueryWrapper<RoutingInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("className", className);
            queryWrapper.eq("type", type);
            queryWrapper.eq("published", true);
            List<RoutingInstance> instances = this.routingInstanceService.list(queryWrapper);
            List<JSONObject> resList = new ArrayList<>();
            instances.forEach(ins->{
                jsonObject.put("id",ins.getId());
                JSONObject upJsonObject = this.updateById(jsonObject);
                resList.add(upJsonObject);
            });
            return resList;
        } catch (Exception ex) {
            throw new BusinessException("999999", "更新模型类型和类名", ex);
        }
    }

    /**
     * 按ids删除模型
     * @param ids id列表
     * @return 返回结果
     */
    public boolean deleteByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            throw new BusinessException("999999", "ids列表不能为空，删除模型失败！");
        }
        //删除缓存
        try {
            QueryWrapper<RoutingInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", ids);
            queryWrapper.eq("published", true);
            queryWrapper.eq("b7", false);
            //删除实例
            this.routingInstanceService.realDelete(queryWrapper);
            this.hierInstanceDslService.deleteByContainerIdList(ModelType.Routing.getCode(), ids);
            this.hierInstanceDslService.deleteByLinkIdList(ModelType.Routing.getCode(), ids);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "按ids删除模型失败！", ex);
        }
    }

    /**
     * 接className删除
     * 1、删除实例、2、删除历史 3、更新redis
     *
     * @param className 模型类名
     * @return 返回值
     */
    @Override
    public boolean deleteByClassName(String className)  {
        if (StringUtils.isBlank(className)) {
            throw new BusinessException("999999", "模型类名称不能为空,删除模型实例失败！");
        }
        //删除缓存
        try {
            QueryWrapper<RoutingInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("className", className);
            queryWrapper.eq("published", true);
            //删除模型
            this.routingInstanceService.realDelete(queryWrapper);
            this.hierInstanceDslService.deleteByClassName(ModelType.Routing.getCode(), className);
            this.hierInstanceDslService.deleteByLinkClassName(ModelType.Routing.getCode(), className);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", String.format("删除模型%s失败!", className), ex);
        }
    }

    /**
     * 批量删除
     *
     * @param classNames 参数
     * @return 返回值
     */
    @Override
    public boolean deleteByClassNames(List<String> classNames) {
        if (classNames == null || classNames.size() < 1) {
            throw new BusinessException("999999", "模型类名称列表不能为空,删除模型实例失败！");
        }
        try {
            QueryWrapper<RoutingInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("className", classNames);
            queryWrapper.eq("published", true);
            //删除实例
            this.routingInstanceService.realDelete(queryWrapper);
            this.hierInstanceDslService.deleteByClassNameList(ModelType.Routing.getCode(), classNames);
            this.hierInstanceDslService.deleteByLinkClassNameList(ModelType.Routing.getCode(), classNames);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "模型类名称列表删除模型失败！");
        }
    }

    /**
     * 按Id 废除模型
     * @param ids 参数
     * @return 返回结果
     */
    public boolean repealByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            throw new BusinessException("999999", "ids列表不能为空，废除模型失败！");
        }
        //删除缓存
        try {
            QueryWrapper<RoutingInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", ids);
            queryWrapper.eq("published", true);
            //删除实例
            this.routingInstanceService.remove(queryWrapper);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "按ids删除模型失败！", ex);
        }

    }

    /**
     * 批量废除
     *
     * @param classNames 参数
     * @return 返回值
     */
    @Override
    public boolean repealByClassNames(List<String> classNames) {
        if (classNames == null || classNames.size() < 1) {
            throw new BusinessException("999999", "模型类名称列表不能为空,删除模型失败！");
        }
        try {
            QueryWrapper<RoutingModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("className", classNames);
            queryWrapper.eq("published", true);
            //删除模型
            this.routingModelService.remove(queryWrapper);
            return true;
        }catch (Exception ex){
            throw new BusinessException("999999", "模型类名称列表删除模型实例失败！");
        }
    }

    /**
     * 获取分页查询
     * @param pageInfo 分页信息
     * @param queryWrapper 查询wrapper
     * @return 返回结果
     */
    private PageInfo getPageInfoResult(Page<RoutingInstance> pageInfo, QueryWrapper<RoutingInstance> queryWrapper,boolean isInfo) {
        Page<RoutingInstance> queryPage = routingInstanceService.page(pageInfo, queryWrapper);
        List<RoutingInstance> records = queryPage.getRecords();
        List<JSONObject> jsonObjectList;
        if(isInfo){
            jsonObjectList = this.getRoutingInsInfoJsonObjectList(records);
        }else{
            records.forEach(r->{
                List<HierInstance> hierInstances = this.hierInstanceDslService.queryByContainerId(ModelType.Routing.getCode(), r.getClassName(), r.getId());
                List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Routing.getCode(), r.getClassName());
                r.setHierInstances(hierInstances);
                r.setHierModels(hierModels);
            });
            jsonObjectList = this.getRoutingInsJsonObjectList(records);
        }
        Page<JSONObject> queryPageDTO = new Page<>();
        BeanUtils.copyProperties(queryPage, queryPageDTO);
        queryPageDTO.setRecords(jsonObjectList);
        return PageInfo.of(queryPageDTO);
    }

    /**
     * 获取分页查询
     * @param pageInfo 分页信息
     * @param queryWrapper 查询wrapper
     * @return 返回结果
     */
    private PageInfo getPageInfoResult(Page<RoutingInstance> pageInfo, QueryWrapper<RoutingInstance> queryWrapper,boolean isInfo, String hierCondition) {
        Page<RoutingInstance> queryPage = routingInstanceService.page(pageInfo, queryWrapper);
        List<RoutingInstance> records = queryPage.getRecords();
        List<JSONObject> jsonObjectList;
        if(isInfo){
            jsonObjectList = this.getRoutingInsInfoJsonObjectList(records);
        }else{
            records.forEach(r->{
                List<HierInstance> hierInstances = hierInstanceDslService.queryByContainerId(ModelType.Routing.getCode(), r.getId(), r.getClassName(), hierCondition);
                List<HierModel> hierModels = this.hierModelDslService.queryByClassName(ModelType.Routing.getCode(), r.getClassName());
                r.setHierInstances(hierInstances);
                r.setHierModels(hierModels);
            });
            jsonObjectList = this.getRoutingInsJsonObjectList(records);
        }
        Page<JSONObject> queryPageDTO = new Page<>();
        BeanUtils.copyProperties(queryPage, queryPageDTO);
        queryPageDTO.setRecords(jsonObjectList);
        return PageInfo.of(queryPageDTO);
    }

    /**
     * 检查模型是否存在
     * @param type 类型
     * @param className 类名称
     * @return 返回是否存，true 存在，false 不存在
     */
    private boolean existModel(String type, String className) {
        QueryWrapper<RoutingModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(type), "type", type);
        queryWrapper.eq(StringUtils.isNotBlank(className), "className", className);
        queryWrapper.eq("published", true);
        long count = this.routingModelService.count(queryWrapper);
        return count > 0;
    }

    /**
     * 将模型实例列表转成JSONObject 列表
     *
     * @param instances 模型实例
     * @return 返回结果
     */
    public List<JSONObject> getRoutingInsInfoJsonObjectList(List<RoutingInstance> instances) {
        List<JSONObject> jsonList = new ArrayList<>();
        instances.forEach(ins -> {
            JSONObject infoJsonObject = ins.getInfoJsonObject();
            jsonList.add(infoJsonObject);

        });
        return jsonList;
    }

    /**
     * 将模型实例列表转成JSONObject 列表
     *
     * @param instances 模型实例
     * @return 返回结果
     */
    public List<JSONObject> getRoutingInsJsonObjectList(List<RoutingInstance> instances) {
        List<RoutingModel> models = this.routingModelService.list();
        List<JSONObject> jsonList = new ArrayList<>();
        instances.forEach(ins -> {
            RoutingModel routingModel = models.stream().filter(m -> m.getClassName().equalsIgnoreCase(ins.getClassName())).findFirst().orElse(null);
            JSONObject insJsonObject = ins.getInsJsonObject(routingModel);
            jsonList.add(insJsonObject);
        });
        return jsonList;
    }

    /**
     * 查询条件字段转换
     *
     * @param condition            参数
     * @param className            参数
     */
    public String transformConditionForRouting(String condition, String className) {
        if (StringUtils.isBlank(condition)) {
            return "";
        }
        if (StringUtils.isBlank(className)) {
            className = queryBuilder.getClassNameBy(condition);
        }
        if (StringUtils.isBlank(className)) {
            return condition;
        }
        if (StringUtils.isNotBlank(className) && StringUtils.isNotBlank(condition)) {
            RoutingModel routingModel = modelCacheDslService.queryModel(ModelType.Routing.getCode(), className);
            if (routingModel != null) {
                List<JSONObject> featureProperties = routingModel.fetchFeatureProperties();
                for (JSONObject item : featureProperties) {
                    String name = item.getString("name");
                    String code = item.getString("code");
                    // condition = condition.replaceAll(name, code);
                    condition = condition.replaceAll("(?<!['%a-z\\d_\\u4e00-\\u9fa5])"+name, code);
                }
                List<JSONObject> featureNoProperties = routingModel.fetchNonFeaturesProperties();
                for (JSONObject item : featureNoProperties) {
                    String name = item.getString("name");
                    condition = condition.replaceAll("(?<!['%a-z0-9_\\u4e00-\\u9fa5])"+name,
                            java.util.regex.Matcher.quoteReplacement("JSON_EXTRACT(insValues,'$.")+name+
                                    "')");
                }
            }
        }
        return condition;
    }

    /**
     * 查询条件字段转换
     *
     * @param condition 取className 条件
     * @param className 类名
     * @param orderBy   排序参数
     */
    public String transformOrderByForRouting(String condition, String className, String orderBy) {
        if (StringUtils.isBlank(orderBy)) {
            return "";
        }
        if (StringUtils.isBlank(className)) {
            className = queryBuilder.getClassNameBy(condition);
        }

        if (StringUtils.isBlank(className)) {
            return orderBy;
        }
        orderBy = orderBy.replaceAll(" ", "");
        RoutingModel routingModel = modelCacheDslService.queryModel("routing", className);
        List<JSONObject> featureProperties = routingModel.fetchFeatureProperties();
        for (JSONObject item : featureProperties) {
            String name = item.getString("name");
            String code = item.getString("code");
            orderBy = orderBy.replaceAll(name, code);
        }
        return orderBy;
    }

    @Override
    public RoutingInstance getById(Long id) {
        return routingInstanceService.getById(id);
    }



    /**
     * 更新节点的状态
     * 1. 更新hierInstance的状态，即节点状态
     * 2. 判断是否为已完成状态
     *  2.1 如果为已完成状态，判断是否所有下级节点都为已完成状态
     *      2.1.1 拿到所有下级节点
     *      2.2.2 判断状态
     *  2.2 如果还有节点未完成，则激活下一节点
     *      2.2.1 拿到后一级节点
     *      2.2.2 激活
     * @param routingInstanceId 当前routing
     * @param statusCode 要更新的状态
     */
    @Override
    public void updateNodeStatus(Long hierLinkId, Long routingInstanceId, String statusCode) {
        RoutingStatusEnum routingStatus = RoutingStatusEnum.getByCode(statusCode);
        HierInstance hierInstance = hierInstanceDslService.fetchByLinkId(ModelType.Routing.getCode(), routingInstanceId, hierLinkId);
        hierInstanceDslService.updateStatus(hierInstance.getId(), statusCode);
        if (routingStatus == RoutingStatusEnum.FINISHED) {
            if (predicateAllNodeFinished(routingInstanceId)) {
                updateStatus(routingInstanceId, RoutingStatusEnum.FINISHED.getCode());
            } else {
                hierInstanceDslService.updateNodeListToReady(hierInstance, predicateCondition);
            }
        }
    }

    /**
     * 判断是否所有子节点为已完成状态
     * @param routingInstanceId 工艺路线实例
     * @return 返回true，false
     */
    public boolean predicateAllNodeFinished(Long routingInstanceId) {
        RoutingInstance routingInstance = getById(routingInstanceId);
        List<HierInstance> hierInstanceList = hierInstanceDslService.queryByContainerId(ModelType.Routing.getCode(), routingInstance.getClassName(), routingInstance.getId());
        long count = hierInstanceList.stream().filter(d -> RoutingStatusEnum.FINISHED.getCode().equals(d.getSt0()))
                .count();
        return hierInstanceList.size() == (int)count + 1;
    }


    /**
     * @param condition
     * @return
     */
    Predicate<String> predicateCondition = condition -> {
        //todo: 校验condition是否为真
        return true;
    };
}
